<?php


namespace App\Http\Controllers\Api;


use App\Constants\SmsConstant;
use App\Models\Member;
use App\Services\SmsService;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class SendSmsController extends Controller
{
    public function send(Request $request)
    {
        $phone = $request->input('phone');
        $type = $request->input('type', SmsConstant::TPL_TYPE_DEFAULT);

        if (!in_array($type, array_keys(SmsConstant::TPL_TYPE_MAP))) {
            return $this->error('type参数错误');
        }

        if ($type == SmsConstant::TPL_TYPE_EXCHANGE_INTEGRAL) {
            $id = auth('api')->user()->id ?? '';
            if (!$id) {
                return $this->error('请先登录', [], 40001, 401);
            }

            $phone = Member::query()->where('id', '=', $id)->value('phone');
        }

        if (!$phone) {
            return $this->error('手机号不能为空');
        }

        $sms = SmsService::instance();
        $ret = $sms->send($phone, $type);
        if (!$ret) {
            return $this->error(Arr::first($sms->getErrors()) ?? '发送失败');
        }

        return $this->success('发送成功');
    }
}
